import os
import re
import requests
from io import BytesIO
from PIL import Image

# ========== 配置区 ==========
BASE_DIR = "./docs"       # Markdown 文件所在目录
OUTPUT_FORMAT = "png"     # 输出格式（png 或 jpg）
OSS_UPLOAD = False         # 是否上传回 OSS（此处先关闭）
# ===========================

# 匹配 Markdown 图片链接: ![](https://...xxx.awebp)
pattern = re.compile(r'!\[.*?\]\((https?://[^\s)]+?\.awebp)\)')

def download_image(url: str):
    """下载图片"""
    try:
        resp = requests.get(url, timeout=15)
        resp.raise_for_status()
        return BytesIO(resp.content)
    except Exception as e:
        print(f"❌ 下载失败: {url} ({e})")
        return None

def convert_image(image_bytes: BytesIO, out_path: str):
    """将 awebp 转换为目标格式"""
    try:
        im = Image.open(image_bytes).convert("RGBA")
        im.save(out_path, OUTPUT_FORMAT.upper())
        print(f"✅ 转换完成: {out_path}")
        return True
    except Exception as e:
        print(f"❌ 转换失败: {out_path} ({e})")
        return False

def process_markdown(md_path: str):
    """处理单个 Markdown 文件"""
    with open(md_path, "r", encoding="utf-8") as f:
        content = f.read()

    links = pattern.findall(content)
    if not links:
        return

    print(f"\n📘 处理文件: {md_path}")

    for url in links:
        new_url = url.replace(".awebp", f".{OUTPUT_FORMAT}")
        filename = os.path.basename(url).replace(".awebp", f".{OUTPUT_FORMAT}")
        filename = re.sub(r'[<>:"/\\|?*]', "_", filename)
        local_path = os.path.join(os.path.dirname(md_path), filename)
        new_url = os.path.basename(filename)
        # 下载 + 转换
        if not os.path.exists(local_path):
            img_bytes = download_image(url)
            if img_bytes:
                convert_image(img_bytes, local_path)

        # TODO: 如果要上传到 OSS，可以在这里添加上传逻辑
        # new_url = upload_to_oss(local_path)

        # 替换 Markdown 内容中的链接
        content = content.replace(url, new_url)

    # 更新 Markdown 文件
    with open(md_path, "w", encoding="utf-8") as f:
        f.write(content)

    print("📝 Markdown 链接已更新。")

def main():
    """程序主入口"""
    print("🚀 开始批量转换 .awebp → ." + OUTPUT_FORMAT)
    for root, _, files in os.walk(BASE_DIR):
        for file in files:
            if file.endswith(".md"):
                md_path = os.path.join(root, file)
                process_markdown(md_path)
    print("\n🎉 全部处理完成！")

if __name__ == "__main__":
    main()
